import { useSelector } from "react-redux";
import { useNavigate, useMatch } from "react-router-dom";
import React, { useEffect } from "react";

interface Iprops{
    allowed:boolean,
    redirectTo:string,
    children:React.ReactNode
}
function RequireAuth({allowed,redirectTo,children}:Iprops){
    const navigate = useNavigate();
    const match = useMatch(redirectTo);
    const {token} = useSelector((state:any)=>state.auth);
    const isLogin = !!token;

    useEffect(() => {
        if (allowed !== isLogin && !match) {
            navigate(redirectTo);
        }
    }, [allowed, isLogin, match, navigate]);
    
    return allowed === isLogin ? <>{children}</> : <></>;
}

export default RequireAuth